package com.bobi.ecofavor.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author wq
 * @version 1.0
 * @date 2021/03/09 16:26
 */
@Slf4j
@Component
public class HttpUtils {


    /**
     * 发送get请求
     *
     * @param path path
     * @return String
     */
    public static String doGet(String path) throws Exception {
        HttpURLConnection httpConn = null;
        BufferedReader in = null;
        try {
            URL url = new URL(path);
            httpConn = (HttpURLConnection) url.openConnection();
            // 读取响应
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuilder content = new StringBuilder();
                String tempStr = "";
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                while ((tempStr = in.readLine()) != null) {
                    content.append(tempStr);
                }
                return content.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            assert in != null;
            in.close();
            httpConn.disconnect();
        }
        return null;
    }


}
